package com.xoa.service.financialManage.Impl;

import com.xoa.dao.financialManage.IncomeExpensePlanMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.financialManage.IncomeExpensePlanWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.financialManage.IncomeExpensePlanService;
import com.xoa.service.users.UsersPrivService;
import com.xoa.service.users.UsersService;
import com.xoa.util.DateFormat;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.*;

@Service
public class IncomeExpensePlanServiceImpl implements IncomeExpensePlanService {

    @Autowired
    private IncomeExpensePlanMapper planMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UsersPrivService usersPrivService;

    @Autowired
    private UsersService usersService;

    //查询列表
    @Override
    public ToJson findIncomePlan(HttpServletRequest request, IncomeExpensePlanWithBLOBs planWithBLOBs) {
        ToJson toJson=new ToJson(1,"err");
        Map map=new HashMap();
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(planWithBLOBs.getPage());
            pageParams.setPageSize(planWithBLOBs.getLimit());
            pageParams.setUseFlag(true);
            map.put("pageParams",pageParams);
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            map.put("planTypeId",planWithBLOBs.getPlanTypeId()); //计划类型

            map.put("creator",user.getUserId()); //创建人
            map.put("deptId",user.getDeptId()); //部门Id
            map.put("roleId",user.getUserPriv()); //角色Id
            map.put("userId",user.getUserId()); //用户Id

            map.put("planName",planWithBLOBs.getPlanName()); //模糊搜索名称或者编号

            //状态控制 （0-未启动，1-进行中，2结束）
            map.put("planStatus",planWithBLOBs.getPlanStatus());

            //时间(1:最近一周，2：最近一月 ，3：最近三个月)
            if (!StringUtils.checkNull(planWithBLOBs.getTimeStatus())){
                switch (planWithBLOBs.getTimeStatus()){
                    case "1":
                        Map<String, Date> daySevenRange = DateFormat.getDaySevenRange();
                        planWithBLOBs.setPlanCreateTime(daySevenRange.get("startDate"));
                        planWithBLOBs.setPlanCreateTimes(daySevenRange.get("endDate"));
                        break;
                    case "2":
                        Map<String, Date> dayTRange = DateFormat.getDayTRange();
                        planWithBLOBs.setPlanCreateTime(dayTRange.get("startDate"));
                        planWithBLOBs.setPlanCreateTimes(dayTRange.get("endDate"));
                        break;
                    case "3":
                        Map<String, Date> threeDay = DateFormat.getThreeDay();
                        planWithBLOBs.setPlanCreateTime(threeDay.get("startDate"));
                        planWithBLOBs.setPlanCreateTimes(threeDay.get("endDate"));
                        break;
                }
            }

            map.put("planCreateTime",planWithBLOBs.getPlanCreateTime()); //开始时间
            map.put("planCreateTimes",planWithBLOBs.getPlanCreateTimes()); //结束时间
            List<IncomeExpensePlanWithBLOBs> findIncome=planMapper.findIncomePlan(map);
            if (findIncome.size()>0){
                toJson.setObj(findIncome);
                toJson.setTotleNum(pageParams.getTotal());
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //根据ID查询信息
    @Override
    public ToJson findIncomePlanById(HttpServletRequest request, IncomeExpensePlanWithBLOBs planWithBLOBs) {
        ToJson toJson=new ToJson(1,"err");
        try {
            String sqlType = "xoa" + request.getSession().getAttribute("loginDateSouse");

            Map map=new HashMap();
            map.put("planId",planWithBLOBs.getPlanId());
            List<IncomeExpensePlanWithBLOBs> findIncome=planMapper.findIncomePlan(map);
            if (findIncome.size()>0){

                IncomeExpensePlanWithBLOBs incomeExpensePlanWithBLOBs = findIncome.get(0);
                Map map1=new HashMap(); //用来返未知数据

                //已支出Spent 和已收入 Earned
                Map<String, Object> spentOrEarned = planMapper.findSpentOrEarned(incomeExpensePlanWithBLOBs.getPlanId());
                if (spentOrEarned!=null && spentOrEarned.size()>0){
                    map1.put("Spent",spentOrEarned.get("EXPENSE"));
                    map1.put("Earned",spentOrEarned.get("INCOME"));
                }


                //计算预算收支差
                if (incomeExpensePlanWithBLOBs.getExpenseBudget()!=null && incomeExpensePlanWithBLOBs.getIncomeBudget()!=null){
                    BigDecimal budgetSubtract = incomeExpensePlanWithBLOBs.getIncomeBudget().subtract(incomeExpensePlanWithBLOBs.getExpenseBudget());
                    map1.put("budgetSubtract",budgetSubtract);
                }

                if (incomeExpensePlanWithBLOBs.getRealExpense()!=null && incomeExpensePlanWithBLOBs.getRealIncome()!=null){
                    //因为类型不一样所以直接用函数进行计算 //计算总收入-总支出=总收支差
                    BigDecimal subtract = incomeExpensePlanWithBLOBs.getRealExpense().subtract(incomeExpensePlanWithBLOBs.getRealIncome());
                    map1.put("realSubtract",subtract);

                    //用户
                    if (!StringUtils.checkNull(incomeExpensePlanWithBLOBs.getUserIds())) {
                        incomeExpensePlanWithBLOBs.setUserNames(usersService.getUserNameById(incomeExpensePlanWithBLOBs.getUserIds()));
                    }

                    //部门
                    if (!StringUtils.checkNull(incomeExpensePlanWithBLOBs.getDeptIds())) {
                        String[] split = incomeExpensePlanWithBLOBs.getDeptIds().split(",");
                        int[] array = Arrays.asList(split).stream().mapToInt(Integer::parseInt).toArray(); //String数组转为int类型数组jdk8
                        incomeExpensePlanWithBLOBs.setDeptNames(departmentService.getDpNameById(array));
                    }

                    //角色
                    if (!StringUtils.checkNull(incomeExpensePlanWithBLOBs.getRoleIds())) {
                        String[] split2 = incomeExpensePlanWithBLOBs.getRoleIds().split(",");
                        int[] array2 = Arrays.asList(split2).stream().mapToInt(Integer::parseInt).toArray(); //String数组转为int类型数组jdk8
                        incomeExpensePlanWithBLOBs.setRoleNames(usersPrivService.getPrivNameById(array2));
                    }
                }

                if (!StringUtils.checkNull(incomeExpensePlanWithBLOBs.getAttachmentName()) && !StringUtils.checkNull(incomeExpensePlanWithBLOBs.getAttachmentId())) {
                    List<Attachment> revenue = GetAttachmentListUtil.returnAttachment(incomeExpensePlanWithBLOBs.getAttachmentName(), incomeExpensePlanWithBLOBs.getAttachmentId(), sqlType, "revenue");
                    map1.put("AttachmentList",revenue);
                }

                incomeExpensePlanWithBLOBs.setMap(map1);

                toJson.setObject(findIncome.get(0));
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //删除接口
    @Override
    public ToJson deletePlanById(HttpServletRequest request, String strId) {
        ToJson toJson=new ToJson(1,"err");
        try {
            String[] split = strId.split(",");
            int i = planMapper.deleteByStrIds(Arrays.asList(split));
            if (i>0){
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }

        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //编辑和新增接口
    @Override
    public ToJson editOrInsertPlan(HttpServletRequest request, IncomeExpensePlanWithBLOBs planWithBLOBs) {
        ToJson toJson=new ToJson(1,"err");
        try {
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());

            int i=0;
            if (planWithBLOBs.getPlanId()!=null){
                //进行中
                if ( !StringUtils.checkNull(planWithBLOBs.getPlanStatus()) && planWithBLOBs.getPlanStatus().equals("1")){
                    planWithBLOBs.setBeginTime(new Date());
                }else if (!StringUtils.checkNull(planWithBLOBs.getPlanStatus()) && planWithBLOBs.getPlanStatus().equals("2")){
                    //结束
                    planWithBLOBs.setEndTime(new Date());
                }

                i = planMapper.updateByPrimaryKeySelective(planWithBLOBs);
            }else {
                planWithBLOBs.setCreator(user.getUserId()); //创建人
                planWithBLOBs.setPlanCreateTime(new Date()); //创建时间
                //判断是否立即启动
                if (planWithBLOBs.getPlanStatus().equals("1")){
                    planWithBLOBs.setBeginTime(new Date()); //启动时间
                }
                i = planMapper.insertSelective(planWithBLOBs);
            }
            if (i>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //批量修改状态
    @Override
    public ToJson editPlanStatus(HttpServletRequest request, String Field,String value,String strId) {
        ToJson toJson=new ToJson(1,"err");
        try {
            String[] split = strId.split(",");
            int i= planMapper.updatePlanStatus(Field,value,Arrays.asList(split));
            if (i>0){
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }
}
